package m3;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接消息服务器
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);//默认的端口可以省略
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c=f.newConnection().createChannel();//连接

        // 1.定义随机队列 2.定义交换机 3.完成异步绑定
        // 定义随机队列的两种方式：1.所有参数手动提供 2.由服务器自动创建
        String queue = UUID.randomUUID().toString();
        c.queueDeclare(queue, false, true, true, null);// 1.定义随机队列
        c.exchangeDeclare("logs", BuiltinExchangeType.FANOUT);//2.定义交换机
        c.queueBind(queue, "logs", "");//3.完成异步绑定   第三个参数对于fanout交换机无效

        // 正常的从随机队列接收消息
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到： "+msg);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };

        c.basicConsume(queue, true, deliverCallback, cancelCallback);

    }
}
